from django.utils import simplejson as json
from django.http import HttpResponseRedirect, HttpResponse

from fbauthfacade import AUTH_CODE, ACCESS_TOKEN
from urllib import urlencode, splitquery
from cgi import parse_qsl

def _get_request_param(request, name):
    return request.GET[name]

def view_graph(request, path = None):
    if path == 'oauth/access_token':
        return view_oauth_access_token(request)
    if path == 'oauth/authorize':
        return view_oauth_authorize(request)

    # Otherwise, handle normal graph object accesses.
    return HttpResponse(json.dumps(_get_graph_data(path), indent = 1))

def view_oauth_authorize(request):
    # client_id
    ##    for (name, value) in request.GET.iteritems():
    ##        print '    %s: %r' % (name, str(value)[:100])

    redirect_uri = _get_request_param(request, 'redirect_uri')
    url = rebuild_query(redirect_uri, dict(code = AUTH_CODE))
    return HttpResponseRedirect(url)

def view_oauth_access_token(request):
    # client_id
    # client_secret
    # redirect_uri

    code = _get_request_param(request, 'code')
    if code == AUTH_CODE:
        response = dict(access_token = ACCESS_TOKEN)
        return HttpResponse(urlencode(response))

def _get_graph_data(object):
    return dict(name = object, id = 1234,
                link = '/facebook/%s' % object)

def simple_parse_qs(qs):
    # Evaluate only last value for each key-pair parameter.
    r = dict()
    for (name, value) in parse_qsl(qs):
        r[name] = value

    return r

def rebuild_query(original, args):
    # Reduce original query string to dictionary, update with existing
    # dictionary, then rebuild new path with query string.

    (path, query) = splitquery(original)
    if query is None:
        query = args
    else:
        query = simple_parse_qs(query)
        query.update(args)

    return '%s?%s' % (path, urlencode(query))
